package com.cbs.android.component.toast;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * Created by broche on 4/7/16.
 */
public class Toast {
    public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;
    public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;
    private static Toast instance = null;
    private static MyHandler handler;
    private android.widget.Toast toast = null;
    private Context context = null;

    public static void init(Context context) {
        if (instance == null) {
            instance = new Toast(context);
            handler = new MyHandler(instance);
        }
    }

    private Toast(Context context) {
        this.context = context;
    }

    private void _show(ToastConfig config) {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
        toast = android.widget.Toast.makeText(context, config.getContent(), config.getDuration() == Toast.LENGTH_SHORT ? android.widget.Toast.LENGTH_SHORT : android.widget.Toast.LENGTH_LONG);
        if (config.getGravity() != null && config.getOffsetX() != null && config.getOffsetY() != null) {
            toast.setGravity(config.getGravity(), config.getOffsetX(), config.getOffsetY());
        }
        if (config.getMarginHorizental() != null && config.getMarginVertical() != null) {
            toast.setMargin(config.getMarginHorizental(), config.getMarginVertical());
        }
        if (config.getView() != null) {
            toast.setView(config.getView());
            toast.setText(config.getContent());
        }
        toast.show();
    }

    public static void show(String message, int duration) {
        ToastConfig config = new ToastConfig()
                .setContent(message)
                .setDuration(duration);
        show(config);
    }

    public static void show(String message) {
        ToastConfig config = new ToastConfig()
                .setContent(message);
        show(config);
    }

    public static void show(ToastConfig config) {
        if (instance == null) {
            throw new NullPointerException("didn't inited");
        }
        Bundle data = new Bundle();
        Message msg = handler.obtainMessage(0, config);
        msg.setData(data);
        handler.sendMessage(msg);
    }

    private static class MyHandler extends Handler {
        private Toast toast;

        public MyHandler(Toast toast) {
            this.toast = toast;
        }

        @Override
        public void handleMessage(Message msg) {
            ToastConfig config = (ToastConfig) msg.obj;
            toast._show(config);
        }
    }
}
